package com.bawei.composeui2207a.day03

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.bawei.composeui2207a.R
import com.bawei.composeui2207a.model.MovieEntity
import com.bawei.composeui2207a.model.RetrofitManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

/**
 * 作者：赵亮
 * 时间：2024/12/12 16:31
 * 功能：
 */
@Composable
fun Day03_3_网络数据获取() {

    // 1. 数据
    var list = remember {
        SnapshotStateList<MovieEntity.Result>()
    }

    LaunchedEffect(key1 = "") {
        // 启动一个携程
        launch {
            RetrofitManager.apiService.findHotMovieList(1, 4)
                .flowOn(Dispatchers.IO)
                .catch { }
                .collect {
                    list.addAll(it.result)
                }

        }
    }

    // 2. 展示
    Column (modifier = Modifier.padding(start = 10.dp, end = 10.dp, top = 24.dp)){
        Text(text = "电影列表")
        LazyVerticalGrid(
            columns = GridCells.Fixed(2),
            horizontalArrangement = Arrangement.spacedBy(10.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            items(list) {
                Column {
                    AsyncImage(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(15.dp)),
                        placeholder = painterResource(id = R.drawable.profile_picture),
                        error = painterResource(id = R.drawable.zhubajie),
                        //model = "https://img2.baidu.com/it/u=2154632616,3541142511&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1074",
                        model = it.imageUrl,
                        contentDescription = null
                    )
                    Text(text = it.name)
                }
            }
        }
    }
}

@Preview(showSystemUi = true)
@Composable
fun Day03_3_网络数据获取Preview() {
    Day03_3_网络数据获取()
}

